<template>
	<el-drawer v-model="visible" size="100%" :show-close="false">
		<template #header="{ close, titleId, titleClass }">
			<span :id="titleId" :class="titleClass">{{ !dataForm.id ? '新增' : '修改' }}</span>
			<el-button class="btnReturn" @click="close">返回</el-button>
		</template>
		<br />
		<el-steps :active="active">
			<el-step title="步骤 1" description="构建reader" />
			<el-step title="步骤 2" description="构建writer" />
			<el-step title="步骤 3" description="字段映射" />
			<el-step title="步骤 4" description="构建" />
		</el-steps>
		<br />
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px" v-loading="formLoading">
			<!-- reader -->
			<div v-show="active === 1">
				<el-form-item label="名称" prop="taskName">
					<el-input placeholder="请输入名称" v-model="dataForm.taskName"></el-input>
				</el-form-item>
				<el-form-item label="执行器" prop="actuatorId">
					<el-select placeholder="请选择执行器" style="width: 100%" filterable v-model="dataForm.actuatorId">
						<el-option v-for="(item, index) in actuatorData" :value="item.id" :label="item.title + '&nbsp' + item.appName" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="数据库源" prop="readerDatabaseId">
					<el-select placeholder="请选择" style="width: 100%" filterable v-model="dataForm.readerDatabaseId" @change="readerDatabaseChange">
						<el-option v-for="(item, index) in databaseDataList" :value="item.id" :label="item.name" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="数据库表名" prop="readerTables">
					<el-select placeholder="请选择" style="width: 100%" filterable v-model="dataForm.readerTables" @change="reanderTablesChange">
						<el-option v-for="(item, index) in IntegrateList" :value="item.tableName" :label="item.tableName" :key="index">
							{{ item.tableName }}
							<span v-if="item.remarks">({{ item.remarks }})</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="SQL语句" prop="querySql">
					<el-input
						type="textarea"
						style="width: 80%"
						:rows="4"
						v-model="dataForm.querySql"
						placeholder="sql查询，一般用于多表关联查询时才用"
					></el-input>
					<el-button type="primary" style="margin-left: 20px" @click="analysisColumnsSql">解析字段</el-button>
				</el-form-item>
				<el-form-item label="切分字段" prop="readerSplitPk">
					<el-input placeholder="切分主键" v-model="dataForm.readerSplitPk"></el-input>
				</el-form-item>
				<el-form-item label="表所有字段" prop="readerColumns">
					<el-checkbox style="margin-right: 20px" v-model="checkAllReader" :indeterminate="isIndeterminateReader" @change="handleCheckAllReaderChange"
						>全选</el-checkbox
					>
					<div style="margin: 10px 0"></div>
					<el-checkbox-group v-model="dataForm.readerColumns" @change="handleCheckedReaderChange">
						<el-checkbox v-for="city in readerColumnsList" :key="city" :label="city">{{ city }}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="where条件" prop="whereParams">
					<el-input type="textarea" :rows="2" v-model="dataForm.whereParams" placeholder="where条件，不需要在加where"></el-input>
				</el-form-item>
				<el-form-item label="调度类型" prop="taskType">
					<fast-radio-group v-model="dataForm.taskType" dict-type="task_type"></fast-radio-group>
				</el-form-item>
				<el-form-item label="cron表达式" prop="cron" v-if="dataForm.taskType == '3'">
					<el-input v-model="dataForm.cron" placeholder="cron表达式" notrim @blur="notrim(dataForm.cron)"></el-input>
				</el-form-item>
			</div>
			<div v-show="active === 2">
				<el-form-item label="数据库源" prop="writerDatabaseId">
					<el-select placeholder="请选择" style="width: 100%" filterable v-model="dataForm.writerDatabaseId" @change="writerDatabaseChange">
						<el-option v-for="(item, index) in databaseDataList" :value="item.id" :label="item.name" :key="index"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="数据库表名" prop="writerTables">
					<el-select placeholder="请选择" style="width: 100%" filterable v-model="dataForm.writerTables" @change="writerTablesChange">
						<el-option v-for="(item, index) in writerIntegrateList" :value="item.tableName" :label="item.tableName" :key="index">
							{{ item.tableName }}
							<span v-if="item.remarks">({{ item.remarks }})</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="表所有字段" prop="writerColumns">
					<el-checkbox style="margin-right: 20px" v-model="checkAllWriter" :indeterminate="isIndeterminateWriter" @change="handleCheckAllWriterChange"
						>全选</el-checkbox
					>
					<div style="margin: 10px 0"></div>
					<el-checkbox-group v-model="dataForm.writerColumns" @change="handleCheckedWriterChange">
						<el-checkbox v-for="city in writerColumnsList" :key="city" :label="city">{{ city }}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="前置SQL语句" prop="preSql">
					<el-input type="textarea" :rows="2" v-model="dataForm.preSql" placeholder="前置sql在insert之前执行"></el-input>
				</el-form-item>
				<el-form-item label="postSql" prop="postSql">
					<el-input type="textarea" :rows="2" v-model="dataForm.postSql" placeholder="多个用;分隔"></el-input>
				</el-form-item>
			</div>

			<div v-show="active === 3">
				<el-form-item label="源端字段" prop="readerColumns1">
					<el-checkbox
						style="margin-right: 20px"
						v-model="checkAllReader1"
						:indeterminate="isIndeterminateReader1"
						@change="handleCheckAllReaderChange1"
						>全选</el-checkbox
					>
					<div style="margin: 10px 0"></div>
					<el-checkbox-group v-model="dataForm.readerColumns1" @change="handleCheckedReaderChange1">
						<el-checkbox v-for="city in dataForm.readerColumns" :key="city" :label="city">{{ city }}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="目标字段" prop="writerColumns1">
					<el-checkbox
						style="margin-right: 20px"
						v-model="checkAllWriter1"
						:indeterminate="isIndeterminateWriter1"
						@change="handleCheckAllWriterChange1"
						>全选</el-checkbox
					>
					<div style="margin: 10px 0"></div>
					<el-checkbox-group v-model="dataForm.writerColumns1" @change="handleCheckedWriterChange1">
						<el-checkbox v-for="city in dataForm.writerColumns" :key="city" :label="city">{{ city }}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
			</div>
			<div v-show="active === 4" style="height: 400px">
				<el-button type="primary" @click="buildJsonBtn">构建</el-button>
				<el-button @click="copyBtn">复制json</el-button>

				<div style="height: 100%; margin-top: 10px">
					<DataStudioJson ref="dataStudioJsonRef"></DataStudioJson>
				</div>
			</div>
		</el-form>
		<template #footer>
			<el-button v-if="active === 1" @click="visible = false"> 取消 </el-button>
			<el-button v-if="active > 1" @click="pre()"> 上一步 </el-button>
			<el-button type="primary" @click="next()" v-if="active > 0 && active < 4"> 下一步 </el-button>
			<el-button type="primary" @click="submitHandle()" v-if="active == 4"> 提交 </el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts">
import service from '@/utils/request'
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus/es'
import { useAccessApi, useAccessSubmitApi, previewTableNameMap, previewColumnNameMap } from '@/api/data-integrate/access'

import Cron from '@/components/fast-cron/index'
import DataStudioJson from '../../task-scheduling/production/data-studio-json.vue'

import { actuatorDataList, getTableColumns, buildJson, saveDataX, getSqlColumns } from '@/api/task-scheduling'

const emit = defineEmits(['refreshDataList'])

import parser from 'cron-parser'

const visible = ref(false)
const formLoading = ref(false)
const dataFormRef = ref()
const pattern = /[`~!@#$^\-&*()=|{},\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】。，、？\s]/g

const active = ref(1)
const dataForm = reactive({
	taskName: '',
	id: '',
	// actuatorId: 15, // 执行器
	actuatorId: '', // 执行器
	// reader数据库源id
	readerDatabaseId: '',
	// reader 表所有字段
	readerColumns: [],
	// 数据库表名
	readerTables: '',
	querySql: '',
	readerSplitPk: '',
	whereParams: '',

	taskType: '',
	cron: '',
	// writer 数据源id
	writerDatabaseId: '',
	writerTables: '',
	// writer 表所有字段
	writerColumns: [],

	readerColumns1: [], // 源端字段
	writerColumns1: [], // 目标字段
	postSql: '',
	preSql: ''
})

const actuatorData = ref([])

const dataAccessJson = ref('')

onMounted(() => {})

const init = (id?: number) => {
	// 获取执行器列表
	actuatorDataList().then((res: any) => {
		actuatorData.value = res.data
	})

	visible.value = true
	dataForm.id = ''
	dataAccessJson.value = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	active.value = 1

	if (id) {
		getAccess(id)
	} else {
		dataForm.cron = ''
		dataForm.readerDatabaseId = ''
		dataForm.writerDatabaseId = ''

		dataForm.readerTables = ''
		dataForm.writerTables = ''

		dataForm.readerColumns = []
		dataForm.writerColumns = []

		databaseDataList.value = []
		IntegrateList.value = []
		writerIntegrateList.value = []
		readerColumnsList.value = []
		writerColumnsList.value = []
	}

	// 第一步
	getDatabase()
}

const getAccess = (id: number) => {
	useAccessApi(id).then(async res => {
		dataForm.actuatorId = res.data.executeId
		dataForm.taskName = res.data.taskName
		dataForm.readerDatabaseId = res.data.sourceDatabaseId
		dataForm.writerDatabaseId = res.data.targetDatabaseId
		dataForm.taskType = res.data.taskType
		dataForm.cron = res.data.cron
		dataAccessJson.value = res.data.dataxJson
		dataForm.id = res.data.id

		if (res.data.dataxJson) {
			const dataParseJson = JSON.parse(res.data.dataxJson)
			if (dataParseJson.hasOwnProperty('job')) {
				dataForm.readerSplitPk = Object.hasOwnProperty.call(dataParseJson.job.content[0].reader.parameter, 'splitPk')
					? dataParseJson.job.content[0].reader.parameter.splitPk
					: ''

				dataForm.querySql = Object.hasOwnProperty.call(dataParseJson.job.content[0].reader.parameter.connection[0], 'querySql')
					? dataParseJson.job.content[0].reader.parameter.connection[0].querySql[0]
					: ''
				dataForm.querySql = dataForm.querySql.replace(/\\n/g, '\n')

				dataForm.whereParams = Object.hasOwnProperty.call(dataParseJson.job.content[0].reader.parameter, 'where')
					? dataParseJson.job.content[0].reader.parameter.where
					: ''

				dataForm.preSql = Object.hasOwnProperty.call(dataParseJson.job.content[0].reader.parameter, 'preSql')
					? dataParseJson.job.content[0].reader.parameter.preSql
					: ''

				dataForm.postSql = Object.hasOwnProperty.call(dataParseJson.job.content[0].reader.parameter, 'postSql')
					? dataParseJson.job.content[0].reader.parameter.postSql
					: ''

				if (dataParseJson.job.content[0].reader.parameter.connection[0].table) {
					dataForm.readerTables =
						dataParseJson.job.content[0].reader.parameter.connection[0].table[0].split('.')[
							dataParseJson.job.content[0].reader.parameter.connection[0].table[0].split('.').length - 1
						]

					await analysisColumns()
				} else {
					await analysisColumnsSql()
				}
				if (dataParseJson.job.content[0].writer.parameter.connection[0].table) {
					dataForm.writerTables =
						dataParseJson.job.content[0].writer.parameter.connection[0].table[0].split('.')[
							dataParseJson.job.content[0].writer.parameter.connection[0].table[0].split('.').length - 1
						]
					await writerColumnsData()
				}

				if (dataForm.readerDatabaseId) {
					getIntegrate(dataForm.readerDatabaseId)
				}
				if (dataForm.writerDatabaseId) {
					getWriterIntegrate(dataForm.writerDatabaseId)
				}

				dataForm.readerColumns = []
				if (dataParseJson.job.content[0].reader.parameter.column) {
					dataParseJson.job.content[0].reader.parameter.column.forEach(item => {
						dataForm.readerColumns.push(item.replace(pattern, ''))
					})

					if (dataForm.readerColumns.length == readerColumnsList.value.length) {
						checkAllReader.value = true
						isIndeterminateReader.value = false
					} else {
						checkAllReader.value = false
						isIndeterminateReader.value = true
					}
				}

				dataForm.writerColumns = []
				if (dataParseJson.job.content[0].writer.parameter.column) {
					dataParseJson.job.content[0].writer.parameter.column.forEach(item => {
						dataForm.writerColumns.push(item.replace(pattern, ''))
					})

					if (dataForm.writerColumns.length == writerColumnsList.value.length) {
						checkAllWriter.value = true
						isIndeterminateWriter.value = false
					} else {
						checkAllWriter.value = false
						isIndeterminateWriter.value = true
					}
				}

				dataForm.readerColumns1 = dataForm.readerColumns
				dataForm.writerColumns1 = dataForm.writerColumns
			} else {
				dataForm.cron = ''
				dataForm.readerDatabaseId = ''
				dataForm.writerDatabaseId = ''

				dataForm.readerTables = ''
				dataForm.writerTables = ''

				dataForm.readerColumns = []
				dataForm.writerColumns = []

				databaseDataList.value = []
				IntegrateList.value = []
				writerIntegrateList.value = []
				readerColumnsList.value = []
				writerColumnsList.value = []
			}
		} else {
			dataForm.cron = ''
			dataForm.readerDatabaseId = ''
			dataForm.writerDatabaseId = ''

			dataForm.readerTables = ''
			dataForm.writerTables = ''

			dataForm.readerColumns = []
			dataForm.writerColumns = []

			databaseDataList.value = []
			IntegrateList.value = []
			writerIntegrateList.value = []
			readerColumnsList.value = []
			writerColumnsList.value = []
		}
		// dataStudioJsonRef.value.setEditorValue(JSON.stringify(res.data.dataxJson))
	})
}

const notrim = val => {
	dataForm.cron = val.trim()
}

const checkCron = (rule: any, value: any, callback: any) => {
	if (!!value) {
		try {
			let interval = parser.parseExpression(value)
		} catch (e) {
			callback(new Error('请输入正确的cron表达式'))
		}
	} else {
		callback(new Error('必填项不能为空'))
	}

	callback()
}

const dataRules = ref({
	taskName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	actuatorId: [{ required: true, message: '必填项不能为空', trigger: 'change' }],
	readerDatabaseId: [{ required: true, message: '必填项不能为空', trigger: 'change' }],
	// readerTables: [
	// 	{
	// 		trigger: 'change',
	// 		validator: (rule, value, callback) => {
	// 			if ((value && !dataForm.querySql) || (!value && dataForm.querySql)) {
	// 				callback()
	// 			} else {
	// 				callback(new Error('数据库表名,SQL语句选填一项'))
	// 			}
	// 		}
	// 	}
	// ],
	// querySql: [
	// 	{
	// 		trigger: 'change',
	// 		validator: (rule, value, callback) => {
	// 			if ((value && !dataForm.readerTables) || (!value && dataForm.readerTables)) {
	// 				callback()
	// 			} else {
	// 				callback(new Error('数据库表名,SQL语句选填一项'))
	// 			}
	// 		}
	// 	}
	// ],
	taskType: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	cron: [{ required: true, validator: checkCron, trigger: 'blur' }],
	writerDatabaseId: [{ required: true, message: '必填项不能为空', trigger: 'change' }],
	writerTables: [{ required: true, message: '必填项不能为空', trigger: 'change' }]
})

const pre = () => {
	if (active.value-- < 2) active.value = 1
}

//vscode编辑器
const dataStudioJsonRef = ref()
const next = () => {
	if (active.value++ > 4) {
		active.value = 5
	} else if (active.value === 4) {
		dataStudioJsonRef.value.setEditorValue(dataAccessJson.value)
	}
}

const databaseDataList = ref([]) // 数据库源
const IntegrateList = ref([]) // 数据库表名
const writerIntegrateList = ref([]) // 数据库表名
// 第一步
const checkAllReader = ref(false)
const isIndeterminateReader = ref(true)
const readerColumnsList = ref([]) // 表所有字段
const handleCheckAllReaderChange = (val: boolean) => {
	dataForm.readerColumns = val ? readerColumnsList.value : []
	isIndeterminateReader.value = false
}

const handleCheckedReaderChange = (value: string[]) => {
	const checkedCount = value.length
	checkAllReader.value = checkedCount === readerColumnsList.value.length
	isIndeterminateReader.value = checkedCount > 0 && checkedCount < readerColumnsList.value.length
	dataForm.readerColumns = value
	dataForm.readerColumns1 = value
}

// 数据库源切换
const readerDatabaseChange = value => {
	dataForm.readerTables = ''
	getIntegrate(value)
}

// 第二步
const writerTables = ref('') // 数据库表名
const checkAllWriter = ref(false)
const isIndeterminateWriter = ref(true)
const writerColumnsList = ref([]) // 表所有字段

const handleCheckAllWriterChange = (val: boolean) => {
	dataForm.writerColumns = val ? writerColumnsList.value : []
	isIndeterminateWriter.value = false
}
const handleCheckedWriterChange = (value: string[]) => {
	const checkedCount = value.length
	checkAllWriter.value = checkedCount === writerColumnsList.value.length
	isIndeterminateWriter.value = checkedCount > 0 && checkedCount < writerColumnsList.value.length
	dataForm.writerColumns = value
	dataForm.writerColumns1 = value
}

const writerDatabaseChange = value => {
	dataForm.writerTables = ''
	getWriterIntegrate(value)
}

// 第三步
const checkAllReader1 = ref(true)
const isIndeterminateReader1 = ref(false)
const handleCheckAllReaderChange1 = (val: boolean) => {
	dataForm.readerColumns1 = val ? dataForm.readerColumns : []
	isIndeterminateReader1.value = false
}

const handleCheckedReaderChange1 = (value: string[]) => {
	const checkedCount = value.length
	checkAllReader1.value = checkedCount === dataForm.readerColumns.length
	isIndeterminateReader1.value = checkedCount > 0 && checkedCount < dataForm.readerColumns.length
}

const checkAllWriter1 = ref(true)
const isIndeterminateWriter1 = ref(false)

const handleCheckAllWriterChange1 = (val: boolean) => {
	dataForm.writerColumns1 = val ? dataForm.writerColumns : []
	isIndeterminateWriter1.value = false
}
const handleCheckedWriterChange1 = (value: string[]) => {
	const checkedCount = value.length
	checkAllWriter1.value = checkedCount === dataForm.writerColumns.length
	isIndeterminateWriter1.value = checkedCount > 0 && checkedCount < dataForm.writerColumns.length
}

//数据库源
const getDatabase = () => {
	service.get('data-integrate/database').then(res => {
		databaseDataList.value = res.data
		// if (databaseDataList.value) {
		// 	dataForm.readerDatabaseId = res.data.list[0].id
		// 	dataForm.writerDatabaseId = res.data.list[0].id
		// 	getIntegrate(res.data.list[0].id)
		// 	getWriterIntegrate(res.data.list[0].id)
		// }
	})
}

// reader
// 数据库表名
const getIntegrate = (id: string) => {
	service.get(`data-integrate/database/tables/${id}`, {}).then(res => {
		IntegrateList.value = res.data
	})
}

// writer 数据库表名
const getWriterIntegrate = (id: string) => {
	service.get(`data-integrate/database/tables/${id}`, {}).then(res => {
		writerIntegrateList.value = res.data
	})
}

const analysisColumns = async () => {
	readerColumnsList.value = []
	if (dataForm.readerDatabaseId && dataForm.readerTables) {
		await getTableColumns(dataForm.readerDatabaseId, dataForm.readerTables)
			.then(res => {
				formLoading.value = false
				res.data.forEach(element => {
					readerColumnsList.value.push(element.fieldName)
				})

				dataForm.readerColumns = readerColumnsList.value
				checkAllReader.value = true
				isIndeterminateReader.value = false
				dataForm.readerColumns1 = dataForm.readerColumns
				console.log(readerColumnsList.value)
			})
			.catch(() => {
				formLoading.value = false
			})
	}
}

const analysisColumnsSql = async () => {
	if (dataForm.querySql && dataForm.readerDatabaseId) {
		readerColumnsList.value = []
		const commentIndex = dataForm.querySql.replace(/--\s.*$/gm, '').trim()
		
		// await getSqlColumns(dataForm.readerDatabaseId, commentIndex)
			await getSqlColumns(dataForm.readerDatabaseId, ' select * from ( ' + commentIndex.replace(/\n/g, ' ') + ' ) mlsk where 1<>1')
			.then(res => {
				formLoading.value = false
				res.data.forEach(element => {
					readerColumnsList.value.push(element)
				})

				dataForm.readerColumns = readerColumnsList.value
				checkAllReader.value = true
				isIndeterminateReader.value = false
				dataForm.readerColumns1 = dataForm.readerColumns
				console.log(readerColumnsList.value)
			})
			.catch(() => {
				formLoading.value = false
			})
	}
}

const reanderTablesChange = value => {
	formLoading.value = true
	dataForm.readerTables = value

	analysisColumns()
}

const writerTablesChange = value => {
	formLoading.value = true
	dataForm.writerTables = value
	writerColumnsData()
}

const writerColumnsData = async () => {
	writerColumnsList.value = []
	if (dataForm.writerDatabaseId && dataForm.writerTables) {
		await getTableColumns(dataForm.writerDatabaseId, dataForm.writerTables)
			.then(res => {
				formLoading.value = false
				res.data.forEach(element => {
					writerColumnsList.value.push(element.fieldName)
				})

				dataForm.writerColumns = writerColumnsList.value
				checkAllWriter.value = true
				isIndeterminateWriter.value = false
				dataForm.writerColumns1 = dataForm.writerColumns
			})
			.catch(() => {
				formLoading.value = false
			})
	}
}

// 构建
const buildJsonBtn = () => {
	let data = {
		readerDatasourceId: dataForm.readerDatabaseId,
		readerTables: [dataForm.readerTables],
		readerColumns: dataForm.readerColumns1,
		writerDatasourceId: dataForm.writerDatabaseId,
		writerTables: [dataForm.writerTables],
		writerColumns: dataForm.writerColumns1,
		rdbmsReader: {
			readerSplitPk: dataForm.readerSplitPk,
			whereParams: dataForm.whereParams,
			querySql: dataForm.querySql
		},
		rdbmsWriter: {
			preSql: dataForm.preSql,
			postSql: dataForm.postSql
		}
	}

	if (!dataForm.readerColumns1.length) {
		ElMessage.error({
			message: '请选择源端字段',
			duration: 1000
		})

		return false
	}
	if (!dataForm.writerColumns1.length) {
		ElMessage.error({
			message: '请选择目标字段',
			duration: 1000
		})

		return false
	}

	buildJson(data).then(res => {
		dataAccessJson.value = res.data
		// const data = JSON.parse(res.data)

		// data.job.content[0].reader.parameter.connection[0].querySql = []
		// data.job.content[0].reader.parameter.connection[0].querySql.push(
		// 	"select \n    '12330109754405020K'||'-'||a.rec_sn as prm_key, -- 主键\n    '12330109754405020K' as mdc_org_cd, -- 医疗机构代码\n    '浙江萧山医院' as mdc_org_nm, -- 医疗机构名称\n    a.rec_sn as oprt_no, -- 手术流水号\n    '' as elctrnc_apl_no, -- 电子申请单编号\n    '' as otpt_emg_no, -- 门（急）诊号\n    a.ipid as inhos_no, -- 住院号\n    a.pid as pid, -- 患者id\n    --to_date(a.operation_time,'yyyy-mm-dd hh24:mi:ss') \n\t\tto_timestamp(a.operation_time,'yyyymmddhh24miss')::timestamp as oprt_dt_tm, -- 手术操作日期时间\n    --to_date(a.operation_start_time,'yyyy-mm-dd hh24:mi:ss') \n\t\tto_timestamp(a.operation_start_time,'yyyymmddhh24miss')::timestamp as oprt_strt_dt_tm, -- 手术开始日期时间\n    --to_date(a.operation_end_time,'yyyy-mm-dd hh24:mi:ss') \n\t\tto_timestamp(a.operation_end_time,'yyyymmddhh24miss')::timestamp as oprt_end_dt_tm, -- 手术结束日期时间\n    a.dept_code as oprt_dpt_cd, -- 手术科室代码\n    a.dept_name as oprt_dpt_nm, -- 手术科室名称\n    a.operation_doctor_id as oprt_dct_cd, -- 手术医生工号\n    a.operation_doctor as oprt_dct_nm, -- 手术医生姓名\n    a.operation_room_code as oprt_room_cd, -- 手术室编号\n    a.operation_order as oprt_pltfm_cd, -- 手术台号\n    a.operation_code as oprt_cd, -- 手术代码\n    a.operation_name as oprt_nm, -- 手术名称\n    '' as main_oprt_flg, -- 主手术标识\n    case when a.OPERATION_LEVEL in ('Ⅰ类手术','一级') then '1'\n         when a.OPERATION_LEVEL in ('Ⅱ类手术','二级') then '2'\n         when a.OPERATION_LEVEL in ('三级','Ⅲ类手术') then '3'\n         when a.OPERATION_LEVEL in ('Ⅳ类手术','四级') then '4'\n    else '9' end as oprt_lvl_cd, -- 手术级别代码\n    case when a.OPERATION_LEVEL in ('Ⅰ类手术','一级') then '一级手术'\n         when a.OPERATION_LEVEL in ('Ⅱ类手术','二级') then '二级手术'\n         when a.OPERATION_LEVEL in ('三级','Ⅲ类手术') then '三级手术'\n         when a.OPERATION_LEVEL in ('Ⅳ类手术','四级') then '四级手术'\n    else '其他手术' end as oprt_lvl_nm, -- 手术级别名称\n    '' as oprt_prt_cd, -- 手术及操作部位代码\n    '' as oprt_prt_nm, -- 手术及操作部位名称\n    '' as oprt_pstn_cd, -- 手术体位代码\n    '' as oprt_pstn_nm, -- 手术体位名称\n    case when a.cut_grade_name in ('0类切口') then '1'\n         when a.cut_grade_name in ('Ⅰ(介入)','Ⅰ类切口') then '2'\n         when a.cut_grade_name in ('Ⅱ类切口') then '3'\n         when a.cut_grade_name in ('Ⅲ类切口') then '4'\n    else '9' end as oprt_incs_cgy_cd, -- 手术切口类别代码\n    case when a.cut_grade_name in ('0类切口') then '0类切口'\n         when a.cut_grade_name in ('Ⅰ(介入)','Ⅰ类切口') then 'Ⅰ类切口'\n         when a.cut_grade_name in ('Ⅱ类切口') then 'Ⅱ类切口'\n         when a.cut_grade_name in ('Ⅲ类切口') then 'Ⅲ类切口'\n    else '其他' end as oprt_incs_cgy_nm, -- 手术切口类别名称\n    '' as poprt_dos, -- 术前用药\n    '' as intoprt_dos, -- 术中用药\n    '' as oprt_hst_flg, -- 手术史标志\n    '' as wgt, -- 体重(kg)\n    '' as abo_cd, -- abo血型代码\n    '' as abo_nm, -- abo血型名称\n    '' as rh_cd, -- rh血型代码\n    '' as rh_nm, -- rh血型名称\n    '' as poprt_diag_cd, -- 术前诊断编码\n    '' as poprt_diag_nm, -- 术前诊断名称\n    '' as oprt_aftr_diag_cd, -- 术后诊断代码\n    '' as oprt_aftr_diag_nm, -- 术后诊断名称\n    '' as day_oprt_flg, -- 日间手术标志\n    '' as oprt_tp_cd, -- 手术类型代码\n    '' as oprt_tp_nm, -- 手术类型名称\n    '' as oprt_prcs_dscpt, -- 手术过程描述\n    '' as oprt_way_dscpt, -- 操作方法描述\n    '' as oprt_tms, -- 操作次数\n    case when a.heal_grade like '%甲%' then '1'\n         when a.heal_grade like '%乙%' then '2'\n         when a.heal_grade like '%丙%' then '3' \n    else '9' end as oprt_incs_heal_lvl_cd, -- 手术切口愈合等级代码\n    case when a.heal_grade like '%甲%' then '甲'\n         when a.heal_grade like '%乙%' then '乙'\n         when a.heal_grade like '%丙%' then '丙' \n    else '其他' end as oprt_incs_heal_lvl_nm, -- 手术切口愈合等级名称\n    '' as oprt_cplct_flg, -- 手术并发症标志\n    '' as oprt_cplct_dtl_dscpt, -- 手术并发症详细描述\n    '' as oprt_cmplct_flg, -- 手术合并症标识\n    '' as oprt_cmplct_dscpt, -- 手术合并症描述\n    '' as drng_flg, -- 引流标志\n    '' as drng_mtrl_nm, -- 引流材料名称\n    '' as drng_mtrl_qty, -- 引流材料数目\n    '' as plc_prt, -- 放置部位\n    '' as hmhg_vlu, -- 出血量(ml)\n    '' as intoprt_trsfs_itm, -- 术中输液项目\n    '' as trsfs_vlu, -- 输液量(ml)\n    '' as intvt_mtrl_nm, -- 介入物名称\n    '' as skin_dsinfct_dscpt, -- 皮肤消毒描述\n    a.assistant_i_code as fst_oprt_asstnt_cd, -- 第一手术助理医生工号\n    a.assistant_ii_code as scd_oprt_asstnt_cd, -- 第二手术助理医生工号\n    a.assistant_iii_code as tdl_oprt_asstnt_dct_, -- 第三手术助理医生工号\n    a.assistant_iv_code as fthl_oprt_asstnt_dct, -- 第四手术助理医生工号\n    case when a.anesthesia like '%全%' and a.anesthesia like '%+%' then '4'\n         when a.anesthesia like '%全%' then '1' \n    else '3' end as aths_way_cd, -- 麻醉方法代码\n    case when a.anesthesia like '%全%' and a.anesthesia like '%+%' then '复合麻醉'\n         when a.anesthesia like '%全%' then '全身麻醉' \n    else '局部麻醉' end as aths_way_nm, -- 麻醉方法名称\n    a.anesthesia_doctor_code as aths_dct_cd, -- 麻醉医生工号\n    a.anesthesia_doctor as aths_dct_nm, -- 麻醉医生姓名\n    '' as scd_aths_dct_cd, -- 第二麻醉医生工号\n    '' as tdl_aths_dct_cd, -- 第三麻醉医生工号\n    '' as fst_aths_asstnt_dct_cd, -- 第一麻醉助理医生工号\n    '' as scd_aths_asstnt_dct_cd, -- 第二麻醉助理医生工号\n    '' as tdl_aths_asstnt_dct_cd, -- 第三麻醉助理医生工号\n    '' as fthl_aths_asstnt_dct_cd, -- 第四麻醉助理医生工号\n    a.circuit_nurse_code as fst_cct_nus_cd, -- 第一巡回护士工号\n    '' as scd_cct_nus_cd, -- 第二巡回护士工号\n    '' as fst_instrmt_nus_cd, -- 第一器械护士工号\n    '' as scd_instrmt_nus_cd, -- 第二器械护士工号\n    '' as tdl_instrmt_nus_cd, -- 第三器械护士工号\n    '' as elctv_oprt_flg, -- 择期手术标志\n    '' as infct_flg, -- 感染标识\n    --to_date(a.create_time,'yyyy-mm-dd hh24:mi:ss') \n\t\tto_timestamp(a.operation_time,'yyyymmddhh24miss')::timestamp as crt_tm, -- 创建时间\n    a.creator as crt_stff_cd, -- 创建职工工号\n    a.creator_name as crt_stff_nm, -- 创建职工姓名\n    --to_date(a.modify_time,'yyyy-mm-dd hh24:mi:ss') \n\t\tto_timestamp(a.modify_time,'yyyymmddhh24miss')::timestamp as upd_dt, -- 更新日期\n    '12330109754405020K' as upd_mdc_org_cd, -- 更新医疗机构代码\n    '浙江萧山医院' as upd_mdc_org_nm, -- 更新医疗机构名称\n    '' as upd_stff_cd, -- 更新职工工号\n    null as upd_stff_nm, -- 更新职工姓名\n    0 as invld_flg -- 作废标识\nfrom emr.operation_info_rec a  where  \noperation_time is not \t null   and operation_time > to_char((current_date - INTERVAL '5 day' ) , 'yyyy-MM-dd hh24:MI:SS')             \n                "
		// )
		// const dataxJson = JSON.stringify(data)
		// dataStudioJsonRef.value.setEditorValue(dataxJson)
		dataStudioJsonRef.value.setEditorValue(res.data)
	})
}

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			ElMessage({
				message: '请将每一步的参数必填项填写完毕后再提交！',
				type: 'warning'
			})
			return false
		}

		dataAccessJson.value = dataStudioJsonRef.value.getEditorValue()
		if (!dataAccessJson.value) {
			// if (!dataStudioJsonRef.value.getEditorValue() && !dataAccessJson.value) {
			ElMessage({
				message: '请构建Json！',
				type: 'warning'
			})
			return false
		}

		const data = {
			accessMode: 2,
			projectId: 0,
			id: dataForm.id ? dataForm.id : '',
			executeId: dataForm.actuatorId,
			taskName: dataForm.taskName,
			sourceDatabaseId: dataForm.readerDatabaseId,
			targetDatabaseId: dataForm.writerDatabaseId,
			taskType: dataForm.taskType,
			cron: dataForm.cron,
			dataxJson: dataAccessJson.value
		}

		saveDataX(data).then(res => {
			ElMessage({
				message: res.msg,
				type: 'success',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

const copyBtn = () => {
	dataStudioJsonRef.value.copyBtn()
	ElMessage.success({
		message: '复制成功',
		duration: 500
	})
}

defineExpose({
	init
})
</script>

<style scoped>
.tip-content {
	font-size: 14px;
}
</style>
